<template>
  <div class="meetroom-state-page">
    <!-- 顶部筛选区域 -->
    <div class="filter-section">
      <div class="filter-card">
        <div class="select-group">
          <label class="select-label">选择厂区</label>
      <a-select
        v-model="selectedFactoryId"
        placeholder="请选择厂区"
            class="factory-select"
        :options="factoryOptions"
        @change="onFactoryChange"
      />
    </div>

        <!-- 日期标题 -->
        <div class="date-title">
          <h2>会议室占用情况 - {{ formatDisplayDate }}</h2>
        </div>

        <!-- 日期导航 -->
        <div class="date-navigation">
          <a-button type="text" size="small" @click="goToPrevious">
            <IconLeft />
          </a-button>
          <div class="current-date" @click="showDatePicker = true">
            {{ formatDisplayDate }}
    </div>
          <a-button type="text" size="small" @click="goToNext">
            <IconRight />
          </a-button>
          <a-button type="outline" size="small" @click="goToToday">今天</a-button>
  </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content-section">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
      </div>

      <!-- 无数据状态 -->
      <div v-else-if="!meetingRooms.length" class="empty-container">
        <a-empty description="暂无会议室数据" />
      </div>

        <!-- 会议室网格 -->
        <div v-else class="meeting-rooms-grid">
        <div v-for="room in meetingRooms" :key="room.id" class="room-card">
          <div class="room-header">
            <div class="room-info">
              <h3 class="room-name">{{ room.roomName }}</h3>
              <span class="building-name">{{ room.officeBuildingName || room.factoryName }}</span>
            </div>
            <div v-if="isToday()" class="room-status" :class="getRoomStatusClass(room)">
              {{ getRoomStatusText(room) }}
            </div>
          </div>

          <!-- 当日会议概览 -->
          <div class="meetings-overview">
            <div v-if="!getTodayMeetings(room.meetings).length" class="no-meetings">
              当日无会议
            </div>
            <div v-else class="meetings-summary">
              <span class="meeting-count">{{ getTodayMeetings(room.meetings).length }}个会议</span>
              <div class="meeting-tags">
                <span
                  v-for="meeting in getTodayMeetings(room.meetings).slice(0, 2)"
                  :key="meeting.id"
                  class="meeting-tag"
                  :class="getMeetingStatus(meeting)"
                  @click="showMeetingDetail(meeting)"
                >
                  {{ formatShortTime(meeting) }}
                </span>
                <span v-if="getTodayMeetings(room.meetings).length > 2" class="more-meetings">
                  +{{ getTodayMeetings(room.meetings).length - 2 }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 日期选择器弹窗 -->
    <a-modal v-model:visible="showDatePicker" title="选择日期" :footer="false" width="90%">
      <a-calendar v-model="selectedDate" @select="onDateSelect" />
    </a-modal>

    <!-- 会议详情弹窗 -->
    <a-drawer
      v-model:visible="showMeetingDrawer"
      title="会议详情"
      placement="bottom"
      :height="isMobile ? '70%' : '50%'"
    >
      <div v-if="selectedMeeting" class="meeting-detail">
        <div class="detail-item">
          <label>会议标题</label>
          <div>{{ selectedMeeting.title }}</div>
        </div>
        <div class="detail-item">
          <label>会议室</label>
          <div>{{ selectedMeeting.roomName }}</div>
        </div>
        <div class="detail-item">
          <label>会议时间</label>
          <div>{{ selectedMeeting.detailed_time }}</div>
        </div>
        <div class="detail-item">
          <label>召集人</label>
          <div>{{ selectedMeeting.initiator }}</div>
        </div>
        <div class="detail-item">
          <label>所属部门</label>
          <div>{{ selectedMeeting.department }}</div>
        </div>
        <div class="detail-item">
          <label>联系电话</label>
          <div>{{ selectedMeeting.initiator_phone }}</div>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconLeft, IconRight } from '@arco-design/web-vue/es/icon'
import { getFactoryList } from '@/apis/startApp/meeting'
import { getMeetingRoomData } from '@/apis/meet/meetingRoom'

// 响应式数据
const factoryOptions = ref([])
const selectedFactoryId = ref('')
const meetingRooms = ref([])
const loading = ref(false)
// 固定为日视图
const currentViewType = 'day'
const currentDate = ref(new Date())
const selectedDate = ref(new Date())
const showDatePicker = ref(false)
const showMeetingDrawer = ref(false)
const selectedMeeting = ref(null)

// 移动端检测
const isMobile = ref(false)

// 计算属性
const formatDisplayDate = computed(() => {
  const date = currentDate.value
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`
})

// 工具函数
function formatDateString(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 判断选择的日期是否为今天
const isToday = () => {
  const selectedDateStr = formatDateString(currentDate.value)
  const todayStr = formatDateString(new Date())
  return selectedDateStr === todayStr
}

// 获取当前选择日期的会议（包括跨天会议）
const getTodayMeetings = (meetings) => {
  const selectedDateStr = formatDateString(currentDate.value)
  return meetings.filter((meeting) => {
    const startDate = formatDateString(new Date(meeting.start))
    const endDate = formatDateString(new Date(meeting.end))

    // 检查选中日期是否在会议的开始和结束日期之间（包含边界）
    return selectedDateStr >= startDate && selectedDateStr <= endDate
  })
}

// 获取会议状态（支持跨天会议）
const getMeetingStatus = (meeting) => {
  const now = new Date()
  const selectedDateStr = formatDateString(currentDate.value)
  const todayStr = formatDateString(now)
  const startTime = new Date(meeting.start)
  const endTime = new Date(meeting.end)
  const startDate = formatDateString(startTime)
  const endDate = formatDateString(endTime)

  // 只有在查看今天的日期时才显示实时状态
  if (selectedDateStr === todayStr) {
    if (now < startTime) {
      return 'upcoming'
    } else if (now >= startTime && now <= endTime) {
      return 'ongoing'
    } else {
      return 'finished'
    }
  } else {
    // 查看其他日期时的状态判断
    if (startDate === endDate) {
      // 同一天的会议，正常判断
      const currentTimeOnSelectedDate = new Date(currentDate.value)
      currentTimeOnSelectedDate.setHours(now.getHours(), now.getMinutes())

      if (currentTimeOnSelectedDate < startTime) {
        return 'upcoming'
      } else if (currentTimeOnSelectedDate >= startTime && currentTimeOnSelectedDate <= endTime) {
        return 'ongoing'
      } else {
        return 'finished'
      }
    } else {
      // 跨天会议的状态判断
      if (selectedDateStr === startDate) {
        // 会议开始日
        const currentTimeOnSelectedDate = new Date(currentDate.value)
        currentTimeOnSelectedDate.setHours(now.getHours(), now.getMinutes())

        if (currentTimeOnSelectedDate < startTime) {
          return 'upcoming'
        } else {
          return 'ongoing'
        }
      } else if (selectedDateStr === endDate) {
        // 会议结束日
        const currentTimeOnSelectedDate = new Date(currentDate.value)
        currentTimeOnSelectedDate.setHours(now.getHours(), now.getMinutes())

        if (currentTimeOnSelectedDate <= endTime) {
          return 'ongoing'
        } else {
          return 'finished'
        }
      } else {
        // 会议中间的日期，全天进行中
        return 'ongoing'
      }
    }
  }
}

const getMeetingStatusText = (meeting) => {
  const status = getMeetingStatus(meeting)
  switch (status) {
    case 'upcoming': return '即将开始'
    case 'ongoing': return '进行中'
    case 'finished': return '已结束'
    default: return '未知'
  }
}

// 业务方法
const fetchMeetingRoomData = async (factoryId) => {
  if (!factoryId) return

  loading.value = true
  try {
    const dateStr = formatDateString(currentDate.value)
    const params = {
      factoryId: Number(factoryId),
      type: currentViewType,
      date: dateStr
    }

    const res = await getMeetingRoomData(params)
    const dataArr = (res && (res.data || res)) || []

    // 转换数据格式
    meetingRooms.value = Array.isArray(dataArr)
      ? dataArr.map((room) => ({
        id: room?.id || '',
        roomName: room?.roomName || '未知',
        officeBuildingName: room?.officeBuildingName || room?.factoryName || '未知',
        meetings: (room?.occupancyPeriods || []).map((meeting) => ({
          id: meeting?.conferenceId || '',
          title: meeting?.title || '未知',
          roomName: room?.roomName || '未知',
          detailed_time: `${meeting?.start || ''} - ${meeting?.end || ''}`,
          initiator: meeting?.initiator || '未知',
          initiator_phone: meeting?.phone || '未知',
          department: meeting?.department || meeting?.initiatorDepartment || '未知',
          start: meeting?.start || '',
          end: meeting?.end || ''
        }))
      }))
      : []
  } catch (error) {
    console.error('获取会议室数据失败:', error)
    Message.error('获取会议室数据失败')
    meetingRooms.value = []
  } finally {
    loading.value = false
  }
}

const fetchFactoryList = async () => {
  try {
    const res = await getFactoryList()
    if (!Array.isArray(res)) {
      factoryOptions.value = []
      return
    }
    factoryOptions.value = res.map((item) => ({
      label: item?.name || '未知',
      value: item?.id || ''
    }))

    // 默认选中id为254的厂区，如果没有则选第一个
    let defaultFactory = res.find((item) => item?.id === 254)
    if (!defaultFactory && res.length > 0) {
      defaultFactory = res[0]
    }
    if (defaultFactory) {
      selectedFactoryId.value = defaultFactory.id
      await fetchMeetingRoomData(defaultFactory.id)
    }
  } catch (error) {
    console.error('获取厂区列表失败:', error)
    Message.error('获取厂区列表失败')
    factoryOptions.value = []
    selectedFactoryId.value = ''
  }
}

// 事件处理方法
const onFactoryChange = (factoryId) => {
  if (factoryId) {
    fetchMeetingRoomData(factoryId)
  }
}

const goToPrevious = () => {
  const newDate = new Date(currentDate.value)
  newDate.setDate(newDate.getDate() - 1)
  currentDate.value = newDate
  if (selectedFactoryId.value) {
    fetchMeetingRoomData(selectedFactoryId.value)
  }
}

const goToNext = () => {
  const newDate = new Date(currentDate.value)
  newDate.setDate(newDate.getDate() + 1)
  currentDate.value = newDate
  if (selectedFactoryId.value) {
    fetchMeetingRoomData(selectedFactoryId.value)
  }
}

const goToToday = () => {
  currentDate.value = new Date()
  if (selectedFactoryId.value) {
    fetchMeetingRoomData(selectedFactoryId.value)
  }
}

const onDateSelect = (date) => {
  currentDate.value = new Date(date)
  showDatePicker.value = false
  if (selectedFactoryId.value) {
    fetchMeetingRoomData(selectedFactoryId.value)
  }
}

const showMeetingDetail = (meeting) => {
  selectedMeeting.value = meeting
  showMeetingDrawer.value = true
}

const getRoomStatusClass = (room) => {
  // 此函数只会在今天被调用，所以直接判断实时状态
  const now = new Date()
  const currentTime = now.getHours() * 60 + now.getMinutes()
  const todayStr = formatDateString(now)

  for (const meeting of room.meetings) {
    const startTime = new Date(meeting.start)
    const endTime = new Date(meeting.end)
    const startDate = formatDateString(startTime)
    const endDate = formatDateString(endTime)

    // 检查今天是否在会议期间（包括跨天会议）
    if (todayStr >= startDate && todayStr <= endDate) {
      // 对于跨天会议，需要特殊处理时间判断
      if (startDate === endDate) {
        // 同一天的会议，正常判断
        const meetingStart = startTime.getHours() * 60 + startTime.getMinutes()
        const meetingEnd = endTime.getHours() * 60 + endTime.getMinutes()
        if (currentTime >= meetingStart && currentTime <= meetingEnd) {
          return 'occupied'
        }
      } else {
        // 跨天会议
        if (todayStr === startDate) {
          // 会议开始日，从会议开始时间到午夜
          const meetingStart = startTime.getHours() * 60 + startTime.getMinutes()
          if (currentTime >= meetingStart) {
            return 'occupied'
          }
        } else if (todayStr === endDate) {
          // 会议结束日，从午夜到会议结束时间
          const meetingEnd = endTime.getHours() * 60 + endTime.getMinutes()
          if (currentTime <= meetingEnd) {
            return 'occupied'
          }
        } else {
          // 会议中间的日期，全天占用
          return 'occupied'
        }
      }
    }
  }

  return 'available'
}

const getRoomStatusText = (room) => {
  return getRoomStatusClass(room) === 'occupied' ? '使用中' : '空闲'
}

const formatMeetingTime = (meeting) => {
  const start = new Date(meeting.start)
  const end = new Date(meeting.end)
  return `${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')} - ${String(end.getHours()).padStart(2, '0')}:${String(end.getMinutes()).padStart(2, '0')}`
}

// 格式化短时间（只显示开始时间）
const formatShortTime = (meeting) => {
  const start = new Date(meeting.start)
  return `${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')}`
}

// 生命周期
onMounted(() => {
  // 检测移动端
  isMobile.value = window.innerWidth <= 768 || /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)

  // 监听窗口变化
  const handleResize = () => {
    isMobile.value = window.innerWidth <= 768 || /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  }
  window.addEventListener('resize', handleResize)

  // 初始化数据
  fetchFactoryList()

  // 清理事件监听器
  return () => {
    window.removeEventListener('resize', handleResize)
  }
})
</script>

<style scoped>
/* 主容器 - 修复滚动问题 */
.meetroom-state-page {
  width: 100%;
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 筛选区域 */
.filter-section {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  padding: 12px;
  flex-shrink: 0;
}

.filter-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  max-width: 1400px;
  margin: 0 auto;
}

.select-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.select-label {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.factory-select {
  min-width: 160px;
}

.date-title h2 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.date-navigation {
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-date {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  padding: 6px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 120px;
  text-align: center;
}

.current-date:hover {
  background: #e9ecef;
}

/* 内容区域 - 可滚动 */
.content-section {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

/* 会议室网格 */
.meeting-rooms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
  padding-bottom: 20px;
}

/* 会议室卡片 */
.room-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 12px;
  transition: all 0.2s;
  border: 1px solid #f0f0f0;
}

.room-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-color: #1677ff;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  gap: 8px;
}

.room-info {
  flex: 1;
  min-width: 0;
}

.room-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin: 0 0 2px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.building-name {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.room-status {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  flex-shrink: 0;
}

.room-status.available {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.room-status.occupied {
  background: #fff2e8;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

/* 会议概览 */
.meetings-overview {
  margin-top: 8px;
}

.meetings-overview .no-meetings {
  color: #999;
  text-align: center;
  padding: 8px;
  font-size: 12px;
  background: #fafafa;
  border-radius: 4px;
}

.meetings-summary {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.meeting-count {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.meeting-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.meeting-tag {
  padding: 3px 6px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid;
}

.meeting-tag:hover {
  transform: scale(1.05);
}

.meeting-tag.upcoming {
  background: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.meeting-tag.ongoing {
  background: #f6ffed;
  color: #52c41a;
  border-color: #b7eb8f;
}

.meeting-tag.finished {
  background: #fafafa;
  color: #999;
  border-color: #d9d9d9;
}

.more-meetings {
  padding: 3px 6px;
  border-radius: 4px;
  font-size: 11px;
  color: #666;
  background: #f0f0f0;
  border: 1px solid #d9d9d9;
}

/* 会议详情 */
.meeting-detail {
  padding: 16px;
}

.detail-item {
  margin-bottom: 16px;
}

.detail-item label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  margin-bottom: 4px;
}

.detail-item div {
  font-size: 16px;
  color: #333;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .filter-section {
    padding: 8px;
  }

  .filter-card {
    flex-direction: column;
    gap: 8px;
  }

  .select-group {
    justify-content: center;
  }

  .factory-select {
    min-width: 200px;
  }

  .date-title h2 {
    font-size: 14px;
  }

  .current-date {
    min-width: unset;
    font-size: 12px;
    padding: 4px 8px;
  }

  .content-section {
    padding: 8px;
  }

  .meeting-rooms-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 8px;
  }

  .room-card {
    padding: 10px;
  }

  .room-name {
    font-size: 13px;
  }

  .building-name {
    font-size: 11px;
  }

  .room-status {
    font-size: 10px;
    padding: 2px 6px;
  }

  .meeting-count {
    font-size: 11px;
  }

  .meeting-tag {
    font-size: 10px;
    padding: 2px 4px;
  }

  .more-meetings {
    font-size: 10px;
    padding: 2px 4px;
  }
}

@media (max-width: 480px) {
  .filter-section {
    padding: 6px;
  }

  .content-section {
    padding: 6px;
  }

  .meeting-rooms-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 6px;
  }

  .room-card {
    padding: 8px;
  }

  .date-navigation {
    gap: 4px;
  }

  .current-date {
    padding: 3px 6px;
    font-size: 11px;
  }

  .date-title h2 {
    font-size: 13px;
  }

  .room-name {
    font-size: 12px;
  }

  .building-name {
    font-size: 10px;
  }
}
</style>
